<template>
  <div class="create-template">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-text">
          <h1>🚀 创建模板</h1>
          <p>创建和分享您的项目模板 —— 让创意变成现实</p>
        </div>
        <div class="header-decoration">
          <div class="floating-shapes">
            <div class="shape shape-1"></div>
            <div class="shape shape-2"></div>
            <div class="shape shape-3"></div>
            <div class="shape shape-4"></div>
          </div>
        </div>
      </div>
    </div>

    <!-- 创建步骤 -->
    <el-card class="steps-card mb-4">
      <div class="steps-header">
        <h3>📋 创建流程</h3>
        <p>按照步骤完成模板创建</p>
      </div>
      <el-steps :active="currentStep" finish-status="success" align-center class="custom-steps">
        <el-step title="基础信息" description="填写模板基本信息">
          <template #icon>
            <div class="step-icon step-1">
              <el-icon><Edit /></el-icon>
            </div>
          </template>
        </el-step>
        <el-step title="模板配置" description="配置模板文件和结构">
          <template #icon>
            <div class="step-icon step-2">
              <el-icon><Setting /></el-icon>
            </div>
          </template>
        </el-step>
        <el-step title="预览确认" description="预览并确认模板信息">
          <template #icon>
            <div class="step-icon step-3">
              <el-icon><View /></el-icon>
            </div>
          </template>
        </el-step>
      </el-steps>
    </el-card>

    <!-- 步骤内容 -->
    <el-card class="content-card">
      <!-- 步骤1：基础信息 -->
      <div v-show="currentStep === 0" class="step-content">
        <div class="step-title">
          <h3>📝 基础信息</h3>
          <p>请填写模板的基本信息</p>
        </div>
        <el-form
          ref="basicFormRef"
          :model="templateForm"
          :rules="basicRules"
          label-width="120px"
          size="large"
          class="beautiful-form"
        >
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="模板名称" prop="name" class="form-item-enhanced">
                <el-input
                  v-model="templateForm.name"
                  placeholder="请输入一个有意义的模板名称"
                  clearable
                  class="enhanced-input"
                >
                  <template #prefix>
                    <el-icon><Edit /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="模板版本" prop="version" class="form-item-enhanced">
                <el-input
                  v-model="templateForm.version"
                  placeholder="例如: 1.0.0"
                  clearable
                  class="enhanced-input"
                >
                  <template #prefix>
                    <el-icon><Collection /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="模板分类" prop="category" class="form-item-enhanced">
                <el-select
                  v-model="templateForm.category"
                  placeholder="选择最合适的分类"
                  style="width: 100%"
                  class="enhanced-select"
                >
                  <el-option
                    v-for="category in categories"
                    :key="category.value"
                    :label="category.label"
                    :value="category.value"
                  >
                    <div class="option-item">
                      <span>{{ category.icon }}</span>
                      <span>{{ category.label }}</span>
                    </div>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="技术框架" prop="framework" class="form-item-enhanced">
                <el-select
                  v-model="templateForm.framework"
                  placeholder="选择主要技术框架"
                  style="width: 100%"
                  class="enhanced-select"
                >
                  <el-option
                    v-for="framework in frameworks"
                    :key="framework.value"
                    :label="framework.label"
                    :value="framework.value"
                  >
                    <div class="option-item">
                      <span>{{ framework.icon }}</span>
                      <span>{{ framework.label }}</span>
                    </div>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="模板描述" prop="description" class="form-item-enhanced">
            <el-input
              v-model="templateForm.description"
              type="textarea"
              :rows="4"
              placeholder="详细描述您的模板特点、用途和优势..."
              class="enhanced-textarea"
            />
          </el-form-item>

          <el-form-item label="模板标签" prop="tags" class="form-item-enhanced">
            <el-select
              v-model="templateForm.tags"
              multiple
              filterable
              allow-create
              placeholder="选择或创建标签，最多5个"
              style="width: 100%"
              class="enhanced-select"
              :multiple-limit="5"
            >
              <el-option
                v-for="tag in predefinedTags"
                :key="tag"
                :label="tag"
                :value="tag"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="模板缩略图" class="form-item-enhanced">
            <div class="thumbnail-upload-container">
              <el-upload
                class="thumbnail-uploader"
                action="#"
                :show-file-list="false"
                :before-upload="beforeThumbnailUpload"
                :on-success="handleThumbnailSuccess"
              >
                <div v-if="templateForm.thumbnail" class="thumbnail-preview">
                  <img :src="templateForm.thumbnail" class="thumbnail" />
                  <div class="thumbnail-overlay">
                    <el-icon><Plus /></el-icon>
                    <span>重新上传</span>
                  </div>
                </div>
                <div v-else class="thumbnail-placeholder">
                  <el-icon class="upload-icon"><Plus /></el-icon>
                  <div class="upload-text">
                    <p>点击上传缩略图</p>
                    <span>建议尺寸：400x300px</span>
                  </div>
                </div>
              </el-upload>
              <div class="upload-tips">
                <div class="tip-item">
                  <el-icon><Check /></el-icon>
                  <span>支持 JPG、PNG 格式</span>
                </div>
                <div class="tip-item">
                  <el-icon><Check /></el-icon>
                  <span>文件大小不超过 2MB</span>
                </div>
                <div class="tip-item">
                  <el-icon><Check /></el-icon>
                  <span>推荐比例 4:3</span>
                </div>
              </div>
            </div>
          </el-form-item>
        </el-form>
      </div>

      <!-- 步骤2：模板配置 -->
      <div v-show="currentStep === 1" class="step-content">
        <div class="step-title">
          <h3>⚙️ 模板配置</h3>
          <p>配置模板的详细信息和功能特性</p>
        </div>
        <el-form
          ref="configFormRef"
          :model="templateForm"
          :rules="configRules"
          label-width="120px"
          size="large"
          class="beautiful-form"
        >
          <!-- 模板类型选择 -->
          <el-form-item label="模板类型" prop="templateType" class="form-item-enhanced">
            <el-radio-group v-model="templateForm.templateType" @change="handleTemplateTypeChange" class="template-type-group">
              <el-radio value="file" class="type-radio">
                <div class="radio-content">
                  <div class="radio-icon">📄</div>
                  <div class="radio-text">
                    <div class="radio-title">文件模板</div>
                    <div class="radio-desc">单个或少量文件的模板</div>
                  </div>
                </div>
              </el-radio>
              <el-radio value="project" class="type-radio">
                <div class="radio-content">
                  <div class="radio-icon">📁</div>
                  <div class="radio-text">
                    <div class="radio-title">项目模板</div>
                    <div class="radio-desc">完整的项目结构模板</div>
                  </div>
                </div>
              </el-radio>
              <el-radio value="component" class="type-radio">
                <div class="radio-content">
                  <div class="radio-icon">🧩</div>
                  <div class="radio-text">
                    <div class="radio-title">组件模板</div>
                    <div class="radio-desc">可复用的组件模板</div>
                  </div>
                </div>
              </el-radio>
            </el-radio-group>
          </el-form-item>

          <!-- 文件上传区域 -->
          <el-form-item label="模板文件" prop="files" class="form-item-enhanced">
            <div class="file-upload-container">
              <el-upload
                class="template-uploader"
                drag
                action="#"
                multiple
                :file-list="templateForm.files"
                :before-upload="beforeFileUpload"
                :on-change="handleFileChange"
                :on-remove="handleFileRemove"
              >
                <div class="upload-dragger-content">
                  <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
                  <div class="el-upload__text">
                    <p>将文件拖到此处，或<em>点击上传</em></p>
                    <span>支持 .zip, .tar.gz 压缩包或单个文件</span>
                  </div>
                </div>
              </el-upload>
              <div class="upload-stats" v-if="templateForm.files.length > 0">
                <div class="stats-item">
                  <el-icon><Document /></el-icon>
                  <span>{{ templateForm.files.length }} 个文件</span>
                </div>
                <div class="stats-item">
                  <el-icon><Folder /></el-icon>
                  <span>{{ getTotalSize() }}</span>
                </div>
              </div>
            </div>
          </el-form-item>

          <!-- 项目结构预览 -->
          <el-form-item label="项目结构" v-if="templateForm.templateType === 'project'" class="form-item-enhanced">
            <el-card class="project-structure">
              <template #header>
                <div class="structure-header">
                  <div class="header-left">
                    <el-icon><Folder /></el-icon>
                    <span>项目文件结构</span>
                  </div>
                  <el-button type="text" @click="refreshStructure" class="refresh-btn">
                    <el-icon><Refresh /></el-icon>
                    刷新
                  </el-button>
                </div>
              </template>
              <el-tree
                :data="projectStructure"
                :props="treeProps"
                default-expand-all
                :expand-on-click-node="false"
                class="structure-tree"
              >
                <template #default="{ node, data }">
                  <div class="tree-node">
                    <el-icon v-if="data.type === 'folder'" class="folder-icon"><Folder /></el-icon>
                    <el-icon v-else class="file-icon"><Document /></el-icon>
                    <span class="node-label">{{ node.label }}</span>
                    <el-tag v-if="data.size" size="small" type="info" class="size-tag">{{ data.size }}</el-tag>
                  </div>
                </template>
              </el-tree>
            </el-card>
          </el-form-item>

          <!-- 模板配置 -->
          <el-form-item label="功能特性" class="form-item-enhanced">
            <el-card class="config-options">
              <template #header>
                <div class="config-header">
                  <el-icon><Setting /></el-icon>
                  <span>选择模板包含的功能特性</span>
                </div>
              </template>
              <el-checkbox-group v-model="templateForm.features" class="features-group">
                <el-row :gutter="16">
                  <el-col :span="8" v-for="feature in availableFeatures" :key="feature.value">
                    <el-checkbox :label="feature.value" class="feature-checkbox">
                      <div class="checkbox-content">
                        <span class="feature-icon">{{ feature.icon }}</span>
                        <div class="feature-text">
                          <div class="feature-title">{{ feature.label }}</div>
                          <div class="feature-desc">{{ feature.desc }}</div>
                        </div>
                      </div>
                    </el-checkbox>
                  </el-col>
                </el-row>
              </el-checkbox-group>
            </el-card>
          </el-form-item>

          <!-- 依赖管理 -->
          <el-form-item label="项目依赖" class="form-item-enhanced">
            <el-card class="dependencies-card">
              <template #header>
                <div class="deps-header">
                  <div class="header-left">
                    <el-icon><Box /></el-icon>
                    <span>项目依赖管理</span>
                  </div>
                  <el-tag type="info">{{ templateForm.dependencies.length }} 个依赖</el-tag>
                </div>
              </template>
              
              <el-table :data="templateForm.dependencies" stripe class="deps-table">
                <el-table-column prop="name" label="依赖名称" min-width="200">
                  <template #default="{ row }">
                    <div class="dep-name">
                      <el-icon><Box /></el-icon>
                      <span>{{ row.name }}</span>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="version" label="版本" width="120" />
                <el-table-column prop="type" label="类型" width="120">
                  <template #default="{ row }">
                    <el-tag :type="row.type === 'dependencies' ? 'primary' : 'info'" size="small">
                      {{ row.type === 'dependencies' ? '生产' : '开发' }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="100">
                  <template #default="{ $index }">
                    <el-button
                      type="danger"
                      size="small"
                      text
                      @click="removeDependency($index)"
                      class="remove-btn"
                    >
                      <el-icon><Delete /></el-icon>
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              
              <div class="add-dependency">
                <div class="add-dep-title">
                  <el-icon><Plus /></el-icon>
                  <span>添加新依赖</span>
                </div>
                <el-row :gutter="16">
                  <el-col :span="8">
                    <el-input 
                      v-model="newDependency.name" 
                      placeholder="依赖名称 (如: vue)"
                      class="dep-input"
                    />
                  </el-col>
                  <el-col :span="6">
                    <el-input 
                      v-model="newDependency.version" 
                      placeholder="版本号"
                      class="dep-input"
                    />
                  </el-col>
                  <el-col :span="6">
                    <el-select v-model="newDependency.type" placeholder="类型" class="dep-select">
                      <el-option label="生产依赖" value="dependencies" />
                      <el-option label="开发依赖" value="devDependencies" />
                    </el-select>
                  </el-col>
                  <el-col :span="4">
                    <el-button type="primary" @click="addDependency" class="add-btn">
                      <el-icon><Plus /></el-icon>
                      添加
                    </el-button>
                  </el-col>
                </el-row>
              </div>
            </el-card>
          </el-form-item>
        </el-form>
      </div>

      <!-- 步骤3：预览确认 -->
      <div v-show="currentStep === 2" class="step-content">
        <div class="step-title">
          <h3>👀 预览确认</h3>
          <p>最后检查一遍模板信息，确认无误后即可创建</p>
        </div>
        <div class="template-preview">
          <el-row :gutter="24">
            <el-col :span="12">
              <el-card class="preview-card info-card">
                <template #header>
                  <div class="card-header">
                    <el-icon><InfoFilled /></el-icon>
                    <span>模板信息</span>
                  </div>
                </template>
                <div class="preview-content">
                  <div class="preview-item">
                    <div class="item-label">
                      <el-icon><Edit /></el-icon>
                      <span>模板名称</span>
                    </div>
                    <div class="item-value">{{ templateForm.name }}</div>
                  </div>
                  <div class="preview-item">
                    <div class="item-label">
                      <el-icon><Collection /></el-icon>
                      <span>版本</span>
                    </div>
                    <div class="item-value">{{ templateForm.version }}</div>
                  </div>
                  <div class="preview-item">
                    <div class="item-label">
                      <el-icon><Grid /></el-icon>
                      <span>分类</span>
                    </div>
                    <div class="item-value">{{ getCategoryLabel(templateForm.category) }}</div>
                  </div>
                  <div class="preview-item">
                    <div class="item-label">
                      <el-icon><Cpu /></el-icon>
                      <span>框架</span>
                    </div>
                    <div class="item-value">{{ getFrameworkLabel(templateForm.framework) }}</div>
                  </div>
                  <div class="preview-item">
                    <div class="item-label">
                      <el-icon><Document /></el-icon>
                      <span>描述</span>
                    </div>
                    <div class="item-value description">{{ templateForm.description }}</div>
                  </div>
                  <div class="preview-item">
                    <div class="item-label">
                      <el-icon><PriceTag /></el-icon>
                      <span>标签</span>
                    </div>
                    <div class="item-value">
                      <el-tag
                        v-for="tag in templateForm.tags"
                        :key="tag"
                        class="tag-item"
                        type="primary"
                        effect="light"
                      >
                        {{ tag }}
                      </el-tag>
                      <span v-if="templateForm.tags.length === 0" class="no-data">暂无标签</span>
                    </div>
                  </div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="12">
              <el-card class="preview-card thumbnail-card">
                <template #header>
                  <div class="card-header">
                    <el-icon><Picture /></el-icon>
                    <span>缩略图预览</span>
                  </div>
                </template>
                <div class="thumbnail-preview-container">
                  <div v-if="templateForm.thumbnail" class="thumbnail-preview">
                    <img :src="templateForm.thumbnail" alt="模板缩略图" />
                    <div class="image-info">
                      <el-icon><Check /></el-icon>
                      <span>缩略图已设置</span>
                    </div>
                  </div>
                  <div v-else class="no-thumbnail">
                    <el-icon><Picture /></el-icon>
                    <span>暂无缩略图</span>
                    <p>建议上传缩略图以提高模板吸引力</p>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>

          <el-row :gutter="24" style="margin-top: 24px;">
            <el-col :span="12">
              <el-card class="preview-card config-card">
                <template #header>
                  <div class="card-header">
                    <el-icon><Setting /></el-icon>
                    <span>模板配置</span>
                  </div>
                </template>
                <div class="config-content">
                  <div class="config-section">
                    <div class="section-title">
                      <el-icon><Grid /></el-icon>
                      <span>模板类型</span>
                    </div>
                    <div class="section-value">
                      <el-tag type="success">{{ getTemplateTypeLabel(templateForm.templateType) }}</el-tag>
                    </div>
                  </div>
                  
                  <div class="config-section">
                    <div class="section-title">
                      <el-icon><Star /></el-icon>
                      <span>功能特性</span>
                    </div>
                    <div class="section-value">
                      <el-tag
                        v-for="feature in templateForm.features"
                        :key="feature"
                        class="feature-tag"
                        type="primary"
                        effect="light"
                      >
                        {{ getFeatureLabel(feature) }}
                      </el-tag>
                      <span v-if="templateForm.features.length === 0" class="no-data">暂无特性</span>
                    </div>
                  </div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="12">
              <el-card class="preview-card stats-card">
                <template #header>
                  <div class="card-header">
                    <el-icon><DataAnalysis /></el-icon>
                    <span>统计信息</span>
                  </div>
                </template>
                <div class="stats-content">
                  <div class="stat-item">
                    <div class="stat-icon">
                      <el-icon><Document /></el-icon>
                    </div>
                    <div class="stat-info">
                      <div class="stat-value">{{ templateForm.files.length }}</div>
                      <div class="stat-label">文件数量</div>
                    </div>
                  </div>
                  <div class="stat-item">
                    <div class="stat-icon">
                      <el-icon><Box /></el-icon>
                    </div>
                    <div class="stat-info">
                      <div class="stat-value">{{ templateForm.dependencies.length }}</div>
                      <div class="stat-label">依赖数量</div>
                    </div>
                  </div>
                  <div class="stat-item">
                    <div class="stat-icon">
                      <el-icon><PriceTag /></el-icon>
                    </div>
                    <div class="stat-info">
                      <div class="stat-value">{{ templateForm.tags.length }}</div>
                      <div class="stat-label">标签数量</div>
                    </div>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="step-actions">
        <el-button 
          v-if="currentStep > 0" 
          @click="prevStep" 
          size="large"
          class="action-btn prev-btn"
        >
          <el-icon><ArrowLeft /></el-icon>
          上一步
        </el-button>
        <el-button
          v-if="currentStep < 2"
          type="primary"
          @click="nextStep"
          size="large"
          class="action-btn next-btn"
        >
          下一步
          <el-icon><ArrowRight /></el-icon>
        </el-button>
        <el-button
          v-if="currentStep === 2"
          type="success"
          @click="submitTemplate"
          :loading="submitting"
          size="large"
          class="action-btn create-btn"
        >
          <el-icon v-if="!submitting"><Check /></el-icon>
          {{ submitting ? '创建中...' : '创建模板' }}
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus, UploadFilled, Refresh, Folder, Document, Picture,
  Edit, Setting, View, Check, ArrowLeft, ArrowRight,
  Collection, Grid, PriceTag, InfoFilled, Cpu, Star,
  DataAnalysis, Box, Delete, ArrowDown
} from '@element-plus/icons-vue'

const router = useRouter()

// 响应式数据
const currentStep = ref(0)
const submitting = ref(false)
const basicFormRef = ref(null)
const configFormRef = ref(null)

// 表单数据
const templateForm = reactive({
  name: '',
  version: '1.0.0',
  category: '',
  framework: '',
  description: '',
  tags: [],
  thumbnail: '',
  templateType: 'project',
  files: [],
  features: [],
  dependencies: []
})

// 新依赖数据
const newDependency = reactive({
  name: '',
  version: '',
  type: 'dependencies'
})

// 分类选项（增强版）
const categories = ref([
  { label: '管理后台', value: 'admin', icon: '🎛️' },
  { label: '电商平台', value: 'ecommerce', icon: '🛒' },
  { label: '企业官网', value: 'corporate', icon: '🏢' },
  { label: '博客系统', value: 'blog', icon: '📝' },
  { label: '数据可视化', value: 'dashboard', icon: '📊' },
  { label: '移动应用', value: 'mobile', icon: '📱' },
  { label: '社交网络', value: 'social', icon: '👥' },
  { label: '教育平台', value: 'education', icon: '🎓' }
])

// 框架选项（增强版）
const frameworks = ref([
  { label: 'Vue 3', value: 'vue3', icon: '💚' },
  { label: 'React', value: 'react', icon: '⚛️' },
  { label: 'Angular', value: 'angular', icon: '🔴' },
  { label: 'Next.js', value: 'nextjs', icon: '⚫' },
  { label: 'Nuxt.js', value: 'nuxtjs', icon: '💚' },
  { label: 'Node.js', value: 'nodejs', icon: '💚' },
  { label: 'Express', value: 'express', icon: '🚀' },
  { label: 'Koa', value: 'koa', icon: '🌿' }
])

// 预定义标签
const predefinedTags = ref([
  '响应式设计', 'TypeScript', 'PWA', '国际化',
  '暗色主题', '移动优先', 'SEO优化', '无服务器',
  '微前端', '组件库', 'UI框架', '数据可视化'
])

// 可用功能特性（增强版）
const availableFeatures = ref([
  { label: '响应式设计', value: 'responsive', icon: '📱', desc: '适配各种屏幕尺寸' },
  { label: 'TypeScript支持', value: 'typescript', icon: '🔷', desc: '静态类型检查' },
  { label: 'PWA支持', value: 'pwa', icon: '📲', desc: '渐进式Web应用' },
  { label: '国际化', value: 'i18n', icon: '🌍', desc: '多语言支持' },
  { label: '暗色主题', value: 'dark-theme', icon: '🌙', desc: '深色模式切换' },
  { label: 'ESLint配置', value: 'eslint', icon: '✅', desc: '代码质量检查' },
  { label: '单元测试', value: 'unit-test', icon: '🧪', desc: '自动化测试' },
  { label: '自动化部署', value: 'ci-cd', icon: '🚀', desc: 'CI/CD流水线' },
  { label: 'Docker支持', value: 'docker', icon: '🐳', desc: '容器化部署' }
])

// 项目结构数据
const projectStructure = ref([
  {
    label: 'src',
    type: 'folder',
    children: [
      { label: 'components', type: 'folder' },
      { label: 'views', type: 'folder' },
      { label: 'utils', type: 'folder' },
      { label: 'main.js', type: 'file', size: '2.1KB' }
    ]
  },
  { label: 'package.json', type: 'file', size: '1.5KB' },
  { label: 'README.md', type: 'file', size: '3.2KB' }
])

// 树形控件配置
const treeProps = {
  children: 'children',
  label: 'label'
}

// 表单验证规则
const basicRules = {
  name: [
    { required: true, message: '请输入模板名称', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择模板分类', trigger: 'change' }
  ],
  framework: [
    { required: true, message: '请选择技术框架', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入模板描述', trigger: 'blur' }
  ]
}

const configRules = {
  templateType: [
    { required: true, message: '请选择模板类型', trigger: 'change' }
  ]
}

// 方法
const nextStep = async () => {
  if (currentStep.value === 0) {
    const valid = await basicFormRef.value.validate()
    if (!valid) return
  } else if (currentStep.value === 1) {
    const valid = await configFormRef.value.validate()
    if (!valid) return
  }
  
  currentStep.value++
}

const prevStep = () => {
  currentStep.value--
}

const handleTemplateTypeChange = (value) => {
  // 根据模板类型调整默认配置
  if (value === 'component') {
    templateForm.features = ['responsive', 'typescript']
  }
}

const beforeThumbnailUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
  }
  return isImage && isLt2M
}

const handleThumbnailSuccess = (response, file) => {
  templateForm.thumbnail = URL.createObjectURL(file.raw)
}

const beforeFileUpload = (file) => {
  const validTypes = [
    'application/zip',
    'application/x-zip-compressed',
    'application/gzip',
    'application/x-tar'
  ]
  
  const isValidType = validTypes.includes(file.type) || file.name.endsWith('.zip') || file.name.endsWith('.tar.gz')
  const isLt50M = file.size / 1024 / 1024 < 50

  if (!isValidType) {
    ElMessage.error('只能上传 .zip 或 .tar.gz 格式的文件!')
  }
  if (!isLt50M) {
    ElMessage.error('文件大小不能超过 50MB!')
  }
  return isValidType && isLt50M
}

const handleFileChange = (file, fileList) => {
  templateForm.files = fileList
}

const handleFileRemove = (file, fileList) => {
  templateForm.files = fileList
}

const refreshStructure = () => {
  ElMessage.info('刷新项目结构...')
}

const getTotalSize = () => {
  const totalBytes = templateForm.files.reduce((sum, file) => sum + (file.size || 0), 0)
  if (totalBytes < 1024) return `${totalBytes} B`
  if (totalBytes < 1024 * 1024) return `${(totalBytes / 1024).toFixed(1)} KB`
  return `${(totalBytes / (1024 * 1024)).toFixed(1)} MB`
}

const addDependency = () => {
  if (!newDependency.name || !newDependency.version) {
    ElMessage.warning('请填写完整的依赖信息')
    return
  }
  
  // 检查是否已存在
  const exists = templateForm.dependencies.find(dep => dep.name === newDependency.name)
  if (exists) {
    ElMessage.warning('该依赖已存在')
    return
  }
  
  templateForm.dependencies.push({ ...newDependency })
  newDependency.name = ''
  newDependency.version = ''
  newDependency.type = 'dependencies'
  ElMessage.success('依赖添加成功')
}

const removeDependency = (index) => {
  templateForm.dependencies.splice(index, 1)
  ElMessage.success('依赖删除成功')
}

const submitTemplate = () => {
  submitting.value = true
  
  // 模拟提交过程
  setTimeout(() => {
    submitting.value = false
    ElMessage.success('模板创建成功!')
    
    ElMessageBox.confirm(
      '模板创建成功！是否要查看模板列表？',
      '创建成功',
      {
        confirmButtonText: '查看列表',
        cancelButtonText: '继续创建',
        type: 'success'
      }
    ).then(() => {
      router.push('/home/template-center/templates')
    }).catch(() => {
      // 重置表单
      Object.keys(templateForm).forEach(key => {
        if (Array.isArray(templateForm[key])) {
          templateForm[key] = []
        } else {
          templateForm[key] = ''
        }
      })
      templateForm.version = '1.0.0'
      templateForm.templateType = 'project'
      currentStep.value = 0
    })
  }, 2000)
}

// 获取标签函数
const getCategoryLabel = (value) => {
  const category = categories.value.find(c => c.value === value)
  return category ? category.label : value
}

const getFrameworkLabel = (value) => {
  const framework = frameworks.value.find(f => f.value === value)
  return framework ? framework.label : value
}

const getTemplateTypeLabel = (value) => {
  const types = {
    'file': '文件模板',
    'project': '项目模板',
    'component': '组件模板'
  }
  return types[value] || value
}

const getFeatureLabel = (value) => {
  const feature = availableFeatures.value.find(f => f.value === value)
  return feature ? feature.label : value
}
</script>

<style scoped lang="scss">
.create-template {
  padding: 24px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  min-height: 100vh;
  
  .page-header {
    position: relative;
    text-align: center;
    margin-bottom: 40px;
    padding: 60px 40px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border-radius: 30px;
    overflow: hidden;
    box-shadow: 0 20px 40px rgba(102, 126, 234, 0.3);
    
    .header-content {
      position: relative;
      z-index: 2;
    }
    
    .header-text {
      h1 {
        font-size: 48px;
        font-weight: 800;
        margin: 0 0 16px 0;
        text-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
        background: linear-gradient(45deg, #fff, #e3f2fd);
        background-clip: text;
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        animation: titleGlow 2s ease-in-out infinite alternate;
      }
      
      p {
        font-size: 20px;
        margin: 0;
        opacity: 0.9;
        font-weight: 300;
        letter-spacing: 0.5px;
      }
    }
    
    .floating-shapes {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      z-index: 1;
      
      .shape {
        position: absolute;
        border-radius: 50%;
        background: rgba(255, 255, 255, 0.1);
        animation: float 6s ease-in-out infinite;
        
        &.shape-1 {
          width: 80px;
          height: 80px;
          top: 15%;
          left: 10%;
          animation-delay: 0s;
        }
        
        &.shape-2 {
          width: 60px;
          height: 60px;
          top: 70%;
          right: 15%;
          animation-delay: 2s;
        }
        
        &.shape-3 {
          width: 100px;
          height: 100px;
          bottom: 15%;
          left: 20%;
          animation-delay: 4s;
        }
        
        &.shape-4 {
          width: 40px;
          height: 40px;
          top: 25%;
          right: 25%;
          animation-delay: 1s;
        }
      }
    }
  }

  .steps-card {
    background: white;
    border-radius: 25px;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
    border: 1px solid rgba(255, 255, 255, 0.8);
    margin-bottom: 32px;
    
    .steps-header {
      text-align: center;
      margin-bottom: 32px;
      
      h3 {
        font-size: 24px;
        font-weight: 700;
        color: #2c3e50;
        margin: 0 0 8px 0;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        background-clip: text;
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
      }
      
      p {
        color: #7f8c8d;
        margin: 0;
        font-size: 16px;
      }
    }
    
    .custom-steps {
      :deep(.el-steps) {
        .el-step {
          .el-step__head {
            .el-step__icon {
              border: none;
              background: transparent;
            }
          }
          
          &.is-process {
            .step-icon {
              background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
              color: white;
              transform: scale(1.1);
            }
          }
          
          &.is-finish {
            .step-icon {
              background: linear-gradient(135deg, #10b981 0%, #059f4f 100%);
              color: white;
            }
          }
        }
      }
      
      .step-icon {
        width: 50px;
        height: 50px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        background: #f5f7fa;
        color: #64748b;
        transition: all 0.3s ease;
        box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
        
        .el-icon {
          font-size: 20px;
        }
      }
    }
    
    :deep(.el-card__body) {
      padding: 40px;
    }
  }

  .content-card {
    background: white;
    border-radius: 25px;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
    border: 1px solid rgba(255, 255, 255, 0.8);
    
    :deep(.el-card__body) {
      padding: 40px;
    }
  }

  .step-content {
    min-height: 500px;
  }
  
  .step-title {
    text-align: center;
    margin-bottom: 40px;
    padding-bottom: 20px;
    border-bottom: 2px solid #f0f2f5;
    
    h3 {
      font-size: 28px;
      font-weight: 700;
      color: #2c3e50;
      margin: 0 0 12px 0;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      background-clip: text;
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
    }
    
    p {
      color: #64748b;
      margin: 0;
      font-size: 16px;
    }
  }

  .beautiful-form {
    .form-item-enhanced {
      margin-bottom: 32px;
      
      :deep(.el-form-item__label) {
        font-weight: 600;
        color: #374151;
        font-size: 16px;
      }
      
      .enhanced-input {
        :deep(.el-input__wrapper) {
          border-radius: 12px;
          box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
          border: 2px solid #e5e7eb;
          transition: all 0.3s ease;
          
          &:hover, &.is-focus {
            box-shadow: 0 6px 20px rgba(102, 126, 234, 0.15);
            border-color: #667eea;
            transform: translateY(-1px);
          }
        }
      }
      
      .enhanced-select, .enhanced-textarea {
        :deep(.el-input__wrapper), :deep(.el-textarea__inner) {
          border-radius: 12px;
          box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
          border: 2px solid #e5e7eb;
          transition: all 0.3s ease;
          
          &:hover, &.is-focus {
            box-shadow: 0 6px 20px rgba(102, 126, 234, 0.15);
            border-color: #667eea;
            transform: translateY(-1px);
          }
        }
      }
      
      .option-item {
        display: flex;
        align-items: center;
        gap: 8px;
        
        span:first-child {
          font-size: 16px;
        }
      }
    }
  }

  .thumbnail-upload-container {
    display: flex;
    gap: 24px;
    align-items: flex-start;
    
    .thumbnail-uploader {
      flex-shrink: 0;
      
      :deep(.el-upload) {
        border: 2px dashed #d1d5db;
        border-radius: 16px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: all 0.3s ease;
        
        &:hover {
          border-color: #667eea;
          transform: translateY(-2px);
          box-shadow: 0 8px 25px rgba(102, 126, 234, 0.15);
        }
      }
      
      .thumbnail-preview {
        position: relative;
        width: 200px;
        height: 150px;
        
        .thumbnail {
          width: 100%;
          height: 100%;
          object-fit: cover;
          border-radius: 14px;
        }
        
        .thumbnail-overlay {
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          background: rgba(0, 0, 0, 0.7);
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          opacity: 0;
          transition: opacity 0.3s ease;
          border-radius: 14px;
          color: white;
          
          .el-icon {
            font-size: 24px;
            margin-bottom: 8px;
          }
        }
        
        &:hover .thumbnail-overlay {
          opacity: 1;
        }
      }
      
      .thumbnail-placeholder {
        width: 200px;
        height: 150px;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
        
        .upload-icon {
          font-size: 36px;
          color: #94a3b8;
          margin-bottom: 12px;
        }
        
        .upload-text {
          text-align: center;
          
          p {
            font-size: 14px;
            font-weight: 600;
            color: #475569;
            margin: 0 0 4px 0;
          }
          
          span {
            font-size: 12px;
            color: #94a3b8;
          }
        }
      }
    }
    
    .upload-tips {
      flex: 1;
      
      .tip-item {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-bottom: 12px;
        color: #64748b;
        font-size: 14px;
        
        .el-icon {
          color: #10b981;
          font-size: 16px;
        }
      }
    }
  }

  .template-type-group {
    display: flex;
    gap: 24px;
    
    .type-radio {
      flex: 1;
      
      :deep(.el-radio__input) {
        display: none;
      }
      
      :deep(.el-radio__label) {
        width: 100%;
        padding: 0;
      }
      
      .radio-content {
        display: flex;
        align-items: center;
        padding: 20px;
        border: 2px solid #e5e7eb;
        border-radius: 16px;
        cursor: pointer;
        transition: all 0.3s ease;
        background: white;
        
        &:hover {
          border-color: #667eea;
          box-shadow: 0 8px 25px rgba(102, 126, 234, 0.15);
          transform: translateY(-2px);
        }
        
        .radio-icon {
          font-size: 32px;
          margin-right: 16px;
        }
        
        .radio-text {
          .radio-title {
            font-size: 16px;
            font-weight: 600;
            color: #374151;
            margin-bottom: 4px;
          }
          
          .radio-desc {
            font-size: 14px;
            color: #6b7280;
          }
        }
      }
      
      &:deep(.el-radio__input.is-checked) ~ .el-radio__label .radio-content {
        border-color: #667eea;
        background: linear-gradient(135deg, rgba(102, 126, 234, 0.05), rgba(118, 75, 162, 0.05));
        box-shadow: 0 8px 25px rgba(102, 126, 234, 0.15);
      }
    }
  }

  .file-upload-container {
    .template-uploader {
      :deep(.el-upload-dragger) {
        border: 2px dashed #d1d5db;
        border-radius: 16px;
        background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
        transition: all 0.3s ease;
        
        &:hover {
          border-color: #667eea;
          background: linear-gradient(135deg, rgba(102, 126, 234, 0.05), rgba(118, 75, 162, 0.05));
        }
      }
      
      .upload-dragger-content {
        padding: 40px;
        text-align: center;
        
        .el-icon--upload {
          font-size: 48px;
          color: #667eea;
          margin-bottom: 16px;
        }
        
        .el-upload__text {
          p {
            font-size: 16px;
            font-weight: 600;
            color: #374151;
            margin: 0 0 8px 0;
            
            em {
              color: #667eea;
              font-style: normal;
            }
          }
          
          span {
            font-size: 14px;
            color: #6b7280;
          }
        }
      }
    }
    
    .upload-stats {
      margin-top: 20px;
      display: flex;
      gap: 24px;
      
      .stats-item {
        display: flex;
        align-items: center;
        gap: 8px;
        color: #64748b;
        font-size: 14px;
        font-weight: 500;
        
        .el-icon {
          color: #667eea;
        }
      }
    }
  }

  .project-structure {
    border-radius: 16px;
    
    .structure-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .header-left {
        display: flex;
        align-items: center;
        gap: 8px;
        font-weight: 600;
        color: #374151;
        
        .el-icon {
          color: #667eea;
        }
      }
      
      .refresh-btn {
        color: #667eea;
        
        &:hover {
          background: rgba(102, 126, 234, 0.1);
        }
      }
    }
    
    .structure-tree {
      .tree-node {
        display: flex;
        align-items: center;
        gap: 8px;
        padding: 4px 0;
        
        .folder-icon {
          color: #f59e0b;
          font-size: 16px;
        }
        
        .file-icon {
          color: #6b7280;
          font-size: 16px;
        }
        
        .node-label {
          font-size: 14px;
          color: #374151;
        }
        
        .size-tag {
          margin-left: auto;
        }
      }
    }
  }

  .config-options {
    border-radius: 16px;
    
    .config-header {
      display: flex;
      align-items: center;
      gap: 8px;
      font-weight: 600;
      color: #374151;
      
      .el-icon {
        color: #667eea;
      }
    }
    
    .features-group {
      .feature-checkbox {
        width: 100%;
        margin-bottom: 16px;
        
        :deep(.el-checkbox__input) {
          margin-right: 12px;
        }
        
        .checkbox-content {
          display: flex;
          align-items: center;
          gap: 12px;
          padding: 16px;
          border: 2px solid #e5e7eb;
          border-radius: 12px;
          transition: all 0.3s ease;
          cursor: pointer;
          
          &:hover {
            border-color: #667eea;
            background: rgba(102, 126, 234, 0.02);
          }
          
          .feature-icon {
            font-size: 20px;
          }
          
          .feature-text {
            .feature-title {
              font-size: 14px;
              font-weight: 600;
              color: #374151;
              margin-bottom: 2px;
            }
            
            .feature-desc {
              font-size: 12px;
              color: #6b7280;
            }
          }
        }
        
        &:deep(.el-checkbox__input.is-checked) ~ .el-checkbox__label .checkbox-content {
          border-color: #667eea;
          background: linear-gradient(135deg, rgba(102, 126, 234, 0.05), rgba(118, 75, 162, 0.05));
        }
      }
    }
  }

  .dependencies-card {
    border-radius: 16px;
    
    .deps-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .header-left {
        display: flex;
        align-items: center;
        gap: 8px;
        font-weight: 600;
        color: #374151;
        
        .el-icon {
          color: #667eea;
        }
      }
    }
    
    .deps-table {
      :deep(.el-table__header) {
        th {
          background: #f8fafc;
        }
      }
      
      .dep-name {
        display: flex;
        align-items: center;
        gap: 8px;
        
        .el-icon {
          color: #667eea;
        }
      }
      
      .remove-btn {
        color: #ef4444;
        
        &:hover {
          background: rgba(239, 68, 68, 0.1);
        }
      }
    }
    
    .add-dependency {
      margin-top: 24px;
      padding: 24px;
      background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
      border-radius: 16px;
      
      .add-dep-title {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-bottom: 16px;
        font-weight: 600;
        color: #374151;
        
        .el-icon {
          color: #667eea;
        }
      }
      
      .dep-input, .dep-select {
        :deep(.el-input__wrapper), :deep(.el-select__wrapper) {
          border-radius: 12px;
        }
      }
      
      .add-btn {
        width: 100%;
        border-radius: 12px;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border: none;
      }
    }
  }

  .template-preview {
    .preview-card {
      border-radius: 20px;
      border: 1px solid #e5e7eb;
      transition: all 0.3s ease;
      
      &:hover {
        box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
        transform: translateY(-2px);
      }
      
      .card-header {
        display: flex;
        align-items: center;
        gap: 8px;
        font-weight: 600;
        color: #374151;
        
        .el-icon {
          color: #667eea;
        }
      }
      
      &.info-card {
        .preview-content {
          .preview-item {
            display: flex;
            align-items: flex-start;
            margin-bottom: 20px;
            
            .item-label {
              display: flex;
              align-items: center;
              gap: 8px;
              min-width: 120px;
              font-weight: 600;
              color: #374151;
              
              .el-icon {
                color: #667eea;
                font-size: 16px;
              }
            }
            
            .item-value {
              flex: 1;
              color: #6b7280;
              
              &.description {
                line-height: 1.6;
              }
              
              .tag-item {
                margin-right: 8px;
                margin-bottom: 6px;
              }
              
              .no-data {
                color: #9ca3af;
                font-style: italic;
              }
            }
          }
        }
      }
      
      &.thumbnail-card {
        .thumbnail-preview-container {
          text-align: center;
          
          .thumbnail-preview {
            img {
              max-width: 100%;
              max-height: 200px;
              border-radius: 12px;
              box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
            }
            
            .image-info {
              display: flex;
              align-items: center;
              justify-content: center;
              gap: 8px;
              margin-top: 12px;
              color: #10b981;
              font-weight: 500;
            }
          }
          
          .no-thumbnail {
            height: 200px;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            color: #9ca3af;
            background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
            border-radius: 12px;
            
            .el-icon {
              font-size: 48px;
              margin-bottom: 12px;
            }
            
            p {
              margin: 8px 0 0 0;
              font-size: 12px;
            }
          }
        }
      }
      
      &.config-card {
        .config-content {
          .config-section {
            margin-bottom: 24px;
            
            .section-title {
              display: flex;
              align-items: center;
              gap: 8px;
              font-size: 16px;
              font-weight: 600;
              color: #374151;
              margin-bottom: 12px;
              
              .el-icon {
                color: #667eea;
              }
            }
            
            .section-value {
              .feature-tag {
                margin-right: 8px;
                margin-bottom: 6px;
              }
              
              .no-data {
                color: #9ca3af;
                font-style: italic;
              }
            }
          }
        }
      }
      
      &.stats-card {
        .stats-content {
          display: flex;
          justify-content: space-around;
          
          .stat-item {
            display: flex;
            flex-direction: column;
            align-items: center;
            text-align: center;
            
            .stat-icon {
              width: 60px;
              height: 60px;
              border-radius: 50%;
              background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
              display: flex;
              align-items: center;
              justify-content: center;
              margin-bottom: 12px;
              
              .el-icon {
                font-size: 24px;
                color: white;
              }
            }
            
            .stat-info {
              .stat-value {
                font-size: 24px;
                font-weight: 700;
                color: #374151;
                margin-bottom: 4px;
              }
              
              .stat-label {
                font-size: 14px;
                color: #6b7280;
              }
            }
          }
        }
      }
    }
  }

  .step-actions {
    margin-top: 40px;
    text-align: center;
    padding-top: 24px;
    border-top: 2px solid #f0f2f5;
    
    .action-btn {
      margin: 0 12px;
      padding: 12px 32px;
      border-radius: 12px;
      font-weight: 600;
      font-size: 16px;
      min-width: 140px;
      transition: all 0.3s ease;
      
      &.prev-btn {
        background: #f8fafc;
        color: #64748b;
        border: 2px solid #e2e8f0;
        
        &:hover {
          background: #e2e8f0;
          color: #475569;
          transform: translateY(-2px);
        }
      }
      
      &.next-btn {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border: none;
        
        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);
        }
      }
      
      &.create-btn {
        background: linear-gradient(135deg, #10b981 0%, #059f4f 100%);
        border: none;
        
        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 8px 25px rgba(16, 185, 129, 0.3);
        }
      }
    }
  }

  .mb-4 {
    margin-bottom: 24px;
  }
}

@keyframes titleGlow {
  0% { text-shadow: 0 4px 8px rgba(0, 0, 0, 0.2); }
  100% { text-shadow: 0 4px 15px rgba(255, 255, 255, 0.3), 0 0 30px rgba(255, 255, 255, 0.2); }
}

@keyframes float {
  0%, 100% { transform: translateY(0px) rotate(0deg); }
  33% { transform: translateY(-20px) rotate(120deg); }
  66% { transform: translateY(-10px) rotate(240deg); }
}

// 响应式设计
@media (max-width: 1200px) {
  .create-template {
    .template-type-group {
      flex-direction: column;
      gap: 16px;
    }
    
    .thumbnail-upload-container {
      flex-direction: column;
      
      .upload-tips {
        margin-top: 16px;
      }
    }
  }
}

@media (max-width: 768px) {
  .create-template {
    padding: 16px;
    
    .page-header {
      padding: 40px 20px;
      
      .header-text h1 {
        font-size: 36px;
      }
      
      .header-text p {
        font-size: 18px;
      }
    }
    
    .steps-card, .content-card {
      :deep(.el-card__body) {
        padding: 24px;
      }
    }
    
    .step-title {
      h3 {
        font-size: 24px;
      }
    }
    
    .template-preview {
      .el-row {
        .el-col {
          margin-bottom: 24px;
        }
      }
    }
    
    .step-actions {
      .action-btn {
        margin: 8px;
        width: calc(100% - 16px);
      }
    }
  }
}
</style>
